import {
  configureStore,
  createAction,
  createReducer,
} from "./@reduxjs/toolkit";
import logger from "redux-logger";

// createAction 简化 actionType 和 actionCreator 的创建

const add = createAction("ADD"); //返回的是一个actionCreator
const minus = createAction("MINUS", (payload) => {
  return {
    payload: payload * 2,
  };
});

// createReducer 简化 createReducer 的创建
const reducer = createReducer({ number: 0 }, (builder) => {
  builder
    .addCase(add, (state) => {
      state.number++;
    })
    .addCase(minus, (state, action) => {
      state.number -= action.payload;
    });
});

// configureStore 简化 仓库 创建，增加 store 可读性
const store = configureStore({
  reducer, // 1. 配置 reducer 处理函数
  middleware: (defaultMiddlewares) => [...defaultMiddlewares(), logger], // 2. 配置 store 中间件
  preloadedState: { number: 5 }, // 3. redux 配置初始状态
});
const valueEl = document.getElementById("value");
function render() {
  valueEl.innerHTML = store.getState().number;
}
render();
store.subscribe(render);
document
  .getElementById("add")
  .addEventListener("click", () => store.dispatch(add()));
document
  .getElementById("minus")
  .addEventListener("click", () => store.dispatch(minus(2)));
document.getElementById("asyncAdd").addEventListener("click", () =>
  store.dispatch((dispatch) => {
    // 内置中间件 defaultMiddlewares 实现的，支持异步
    setTimeout(() => {
      dispatch(add());
    }, 1000);
  })
);
